package com.micro.ai.commons.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

/**
 * MybatisPlus 配置类
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Configuration
public class MybatisPlusConfig {

    /**
     * MybatisPlus 拦截器配置
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        
        // 分页插件
        PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor();
        paginationInterceptor.setDbType(DbType.MYSQL);
        paginationInterceptor.setMaxLimit(1000L);
        interceptor.addInnerInterceptor(paginationInterceptor);
        
        return interceptor;
    }

    /**
     * 元数据处理器（统一版本）
     * 支持多种命名风格
     */
    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                LocalDateTime now = LocalDateTime.now();
                // 支持 createTime 命名
                this.fillStrategy(metaObject, "createTime", now);
                this.fillStrategy(metaObject, "updateTime", now);
                // 支持 createdAt 命名
                this.fillStrategy(metaObject, "createdAt", now);
                this.fillStrategy(metaObject, "updatedAt", now);
                // 其他字段
                this.fillStrategy(metaObject, "deleted", 0);
                this.fillStrategy(metaObject, "version", 1);
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                LocalDateTime now = LocalDateTime.now();
                // 支持两种命名风格
                this.fillStrategy(metaObject, "updateTime", now);
                this.fillStrategy(metaObject, "updatedAt", now);
            }
        };
    }
}
